class DownLoadStaticFile {
    static downLoadSameArea(url = '', totalPage = 1, method = 'get') {
        let form = document.createElement('form');
        let input = document.createElement('input');
        input.setAttribute('name', 'totalPage');
        input.setAttribute('value', totalPage);
        form.appendChild(input);
        form.setAttribute('method', method);
        form.setAttribute('id', 'downLoadFileForm');
        form.setAttribute('style', 'display:none;');
        form.setAttribute('action', url);
        document.querySelector('body').appendChild(form);

        form.submit();
        document
            .querySelector('body')
            .removeChild(document.querySelector('#downLoadFileForm'));
    }
    constructor(base64Data, miniType) {
        this.base64Data = base64Data;
        this.miniType = miniType;
        this.localDataUrl = '';
        this.downLoadUrl = '';
    }
    download() {
        const staticBlob = this.dataURLtoBlob(this.base64Data, this.miniType);
        this.openDownloadDialog(staticBlob, this.miniType);
        this.localDataUrl = staticBlob;
        this.clear();
    }
    clear() {
        URL.revokeObjectURL(this.localDataUrl);
    }
    /**
     *
     * @param {*} base64Data
     * @param {*} type
     */
    dataURLtoBlob = (base64Data, type) => {
        let bstr = atob(base64Data),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: type });
    };
    /**
     *
     * @param {*} url
     * @param {*} saveName
     */
    openDownloadDialog = (url, saveName) => {
        if (typeof url == 'object' && url instanceof Blob) {
            url = URL.createObjectURL(url);
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || '';
        var event;
        if (window.MouseEvent) event = new MouseEvent('click');
        else {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent(
                'click',
                true,
                false,
                window,
                0,
                0,
                0,
                0,
                0,
                false,
                false,
                false,
                false,
                0,
                null
            );
        }
        aLink.dispatchEvent(event);
    };
}

export { DownLoadStaticFile };
